package cn.stylefeng.guns.modular.api.controller;
import cn.stylefeng.guns.modular.api.service.FileService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/api/file")
@Api(description = "文件模块", tags = {"文件模块"})
@Slf4j
public class FileController {

    @Resource
    private FileService fileService;


    /**
     * 上传图片文件七牛云
     * @param files
     * @return
     */
    @RequestMapping(value="/uploads", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData uploadImg(MultipartFile[] files) {


        // 验证非空
        if (StringUtils.isBlank(files[0].getOriginalFilename())) {
            return ResponseData.error("文件为空");
        } else {
            Map<String,List<String>> map = new HashMap<>();
            map = fileService.uploadImgs(files);
            List<String> resultList = map.get("result");
            log.info("图片上传返回结果:"+resultList);

            if (!"error".equals(resultList.get(0))) {
                return ResponseData.success(resultList);
            }
        }
        return ResponseData.success();

    }
    /**
     * 上传单个图片文件七牛云
     * @param file
     * @return
     */
    @RequestMapping(value="/upload", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData upload( MultipartFile file) {


        // 验证非空
        if (StringUtils.isBlank(file.getOriginalFilename())) {
            return ResponseData.error("文件为空");
        } else {
            Map<String,List<String>> map = new HashMap<>();
            MultipartFile[] files = new MultipartFile[1];
            files[0] = file;
            map = fileService.uploadImgs(files);
            List<String> resultList = map.get("result");
            log.info("图片上传返回结果:"+resultList);

            if (!"error".equals(resultList.get(0))) {
                Map<String,String> singleMap = new HashMap<>();
                singleMap.put("src",resultList.get(0));
                return ResponseData.success(0,"success",singleMap);
            }
        }
        return ResponseData.success();

    }
}

